<template>
  <div>
    <el-breadcrumb separator=">">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <el-form :inline="true" class="demo-form-inline">
        <!-- 后边的按钮 -->
        <el-form-item>
          <!-- @click="centerDialogVisible = true" -->
          <el-button type="primary" size="small" @click="centerDialogVisible = true">添加角色</el-button>
        </el-form-item>
        <el-dialog title="添加角色" v-model="centerDialogVisible" width="50%">
          <el-form ref="userformRef" :model="userform" label-position="top">
            <el-form-item label="角色名" :label-width="100" prop="username">
              <el-input class="aa" v-model="userform.username" autocomplete="off" placeholder="请输入角色名" />
            </el-form-item>
            <el-form-item label="角色描述" :label-width="100" prop="password">
              <el-input class="aa" v-model="userform.password" autocomplete="off" placeholder="请输入角色描述" />
            </el-form-item>
          </el-form>
          <!-- 具名插槽 -->
          <span>
            <el-button @click="centerDialogVisible = false">取 消</el-button>
            <el-button type="primary">确 定</el-button>
          </span>
        </el-dialog>
        <!-- 表格 stripe是否显示斑马 data数组,展示的数据,border 是否有边框  -->
        <el-table stripe :data="userData" border>
          <el-table-column type="expand" label="展示" width="80">
            <template v-slot="scope">
              <el-row class="it1" v-for="it1 in scope.row.children" :key="it1.id">
                <el-col :span="6" class="colt1">
                  <el-tag closable @close="delRolesRightId(scope.row, it1.id)">{{ it1.authName }}</el-tag>
                </el-col>
                <el-col :span="18">
                  <el-row class="it2" v-for="it2 in it1.children" :key="it2.id">
                    <el-col :span="6">
                      <el-tag closable type="success" @close="delRolesRightId(scope.row, it2.id)">
                        {{ it2.authName }}
                      </el-tag>
                    </el-col>
                    <el-col :span="18">
                      <el-tag
                        class="tagt3"
                        closable
                        type="warning"
                        v-for="it3 in it2.children"
                        :key="it3.id"
                        @close="delRolesRightId(scope.row, it3.id)"
                      >
                        {{ it3.authName }}
                      </el-tag>
                    </el-col>
                  </el-row>
                </el-col>
              </el-row>
            </template>
          </el-table-column>
          <el-table-column type="index" label="序号" width="80"></el-table-column>
          <el-table-column prop="roleName" label="角色名称" width="150"></el-table-column>
          <el-table-column prop="roleDesc" label="角色描述"></el-table-column>
          <el-table-column label="操作" width="400">
            <template v-slot="scop">
              <el-button type="primary" size="small" class="el-icon-edit">编辑</el-button>
              <el-button type="danger" size="small" class="el-icon-delete">删除</el-button>
              <el-button type="warning" size="small" class="el-icon-setting" @click="getRightTree(scop.row)">
                分配权限
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-form>
    </el-card>
    <!-- 分配权限 -->
    <el-dialog title="分配权限" v-model="dialogTreeVisible" @close="checkedKeys = []">
      <!-- data 显示属性数据 defaultprops 对象的映射关系 show-checknox显示复选框
      node-key代表复选框是否选中 default-checked-keys选中的复选框 default-expand-all默认展开所有 -->
      <el-tree
        ref="roleTree"
        :data="treeData"
        :props="treeProps"
        show-checkbox
        default-expand-all
        node-key="id"
        :default-checked-keys="checkedKeys"
      ></el-tree>
      <span>
        <el-button @click="dialogTreeVisible = false">取 消</el-button>
        <el-button type="primary" @click="updataRight">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ElMessage, ElMessageBox } from 'element-plus'
import request from '@/util/request'
import { onMounted, ref } from 'vue'
// 添加角色对话框是否显示
const centerDialogVisible = ref(false)
// 表格数据
const userData = ref([])
const userform = {
  username: '',
  password: '',
  email: '',
  mobile: '',
}
// 权限对话框
const dialogTreeVisible = ref(false)
// 默认勾选的数组
const checkedKeys: any[] = []
// 获取到角色权限
const aauserData = async () => {
  const { data, meta }: any = await request({
    url: 'roles',
    methods: 'GET',
  })
  // 获取失败
  if (meta.status !== 200) {
    return ElMessage.error('网络异常，稍后重试')
  }
  userData.value = data
  ElMessage.success('获取成功')
}
// 分配权限数据
const treeData = ref([])
// 数据对应
const treeProps = {
  children: 'children',
  label: 'authName',
}

onMounted(() => {
  aauserData()
})
// 删除角色权限
const delRolesRightId = async (role, rightid) => {
  const isconfirm = await ElMessageBox.confirm('确定要删除吗', '提示', {
    confirmButtonText: '确定',
    // 取消按钮文本
    cancelButtonText: '否',
    type: 'warning',
  }).catch(() => {
    return ElMessage.info('取消删除了')
  })
  // 确定的情况
  if (isconfirm !== 'confirm') {
    return
  }
  // 发送数据到后台serve
  const { data, meta } = await request({
    url: `roles/${role.id}/rights/${rightid}`,
    method: 'DELETE',
  })
  if (meta.status !== 200) {
    return ElMessage.error('删除失败')
  }
  // 重新给role的权限赋值
  role.children = data
  ElMessage.success('删除权限成功')
}
// 角色id
const roleid = ref()
// 获取权限列表,tree的形式
const getRightTree = async (role) => {
  const { data, meta } = await request({
    url: '/rights/tree',
    method: 'GET',
  })
  if (meta.status !== 200) {
    return ElMessage.error('网络异常，稍后重试')
  }
  treeData.value = data
  dialogTreeVisible.value = true
  // 页面打开给roleid赋值
  roleid.value = role.id
  role.children.forEach((it1) => {
    it1.children.forEach((it2) => {
      it2.children.forEach((it3) => {
        checkedKeys.push(it3.id)
      })
    })
  })
}
// 确定
const roleTree = ref()
const updataRight = async () => {
  const arr = [roleTree.value.getCheckedKeys(),roleTree.value.getHalfCheckedKeys()]
  const { meta } = await request({
    url: `/roles/${roleid.value}/rights`,
    method: 'POST',
    data: { rids: arr.join(',') },
  })
  if (meta.status !== 200) {
    return ElMessage.error('网络异常 请稍后重试')
  }
  dialogTreeVisible.value = false
  ElMessage.success('分配权限成功')
  aauserData()
}
</script>

<style scoped>
.el-card {
  margin-top: 20px;
}
.aa {
  width: 500px;
}
.it1 {
  margin-top: 20px;
}
.colt1 {
  display: flex;
  align-items: center;
}
.it2 {
  margin-bottom: 10px;
  border-top: 1px solid;
}
.tagt3 {
  margin-right: 10px;
}
</style>
